import { readFileSync, writeFileSync } from "node:fs";
import { CommonParams, I18nConfig, ILogger } from "../types";
import GoGoCode from "gogocode";
import { format } from "prettier";
import parseScript from "./script";
import handleChildNode from "./template/child-node";
import handleAttrs from "./template/attrs";
import handleVBind from "./template/v-bind";
import handleVOn from "./template/v-on";

const parseVue2 = async ({ filePath, CONFIG, logger }: CommonParams) => {
  const text = readFileSync(filePath, "utf-8");
  logger("开始处理文件：" + filePath, "info");
  const sfcAst = GoGoCode(text, { parseOptions: { language: "vue" } });
  /**
   * ===================================================================
   * 处理模板部分
   * ===================================================================
   */
  // 处理子节点（纯文本，插值语法）
  handleChildNode({ sfcAst, CONFIG, logger, filePath });
  // 处理属性（attrs,props）
  handleAttrs({ sfcAst, CONFIG, logger, filePath });
  // 处理v-bind
  handleVBind({ sfcAst, CONFIG, logger, filePath });
  // 处理v-on
  handleVOn({ sfcAst, CONFIG, logger, filePath });
  /**
   * ===================================================================
   * 处理脚本部分
   * ===================================================================
   */
  parseScript({ sfcAst, CONFIG, logger, filePath });
  const code = sfcAst.generate();
  // console.log("🚀 ~ parseVue2 ~ code:", code);
  if (code !== text) {
    const formattedCode = await format(code, { parser: "vue" });
    writeFileSync(filePath, formattedCode, {
      encoding: "utf-8",
    });
  }
};

export default parseVue2;
